/*
 * @Descripttion: 拓展context
 * @version: 
 * @Author: turingchang
 * @Date: 2020-12-16 11:14:48
 * @LastEditors: turingchang
 * @LastEditTime: 2020-12-16 15:39:27
 */

'use strict';
const CustomLogger = require('./../common/log/custom_logger');

const user = Symbol('Context#user');
const token = Symbol('Context#token');
const requestLogger = Symbol('Context#requestLogger');
const start_time = Symbol('Context#start_time');
const end_time = Symbol('Context#end_time');
const interval = Symbol('Context#interval');
const validate_error = Symbol('Context#interval');
const errorAndNeedSuccess = Symbol('errorAndNeedSuccess#interval');
const manual_output = Symbol('Context#manual_output');
const page_index = Symbol('Context#page_index');
const page_size = Symbol('Context#page_size');
const limit = Symbol('Context#limit');
const offset = Symbol('Context#offset');

module.exports = {
    //每次请求都分配一个请求id
    get request_id(){
        return this.app.utils.generator.uid(false);
    } ,
    get request_url(){
        var url =`${this.method.toLowerCase()}:${this.path}`;
        //console.log(this.request.header.host+this.request.url);
        return url;
    },
    get token(){
        var t =this.header.token;
        this.app.token = t;
        return t;
    },
    set token(t){
        this[token] =t;
        this.app.token =t;
    },
    get user(){
        return this[user];
    },
    set user(u){
        this[user]=u;
        this.app.user =u;
    },    
    get start_time() {
        if (!this[start_time]) {
            this[start_time] = start_time;
        }
        return this[start_time];
    },
    set start_time(t) {
        this[start_time]=t;
    },
    get end_time() {
        if (!this[end_time]) {
            this[end_time] = end_time;
        }
        return this[end_time];
    },
    set end_time(t) {
        this[end_time]=t;
    },
    get interval() {
        if (!this[interval]) {
            this[interval] = interval;
        }
        return this[interval];
    },
    set interval(t) {
        this[interval]=t;
    },
    get validate_error() {
        if (!this[validate_error]) {
            this[validate_error] = validate_error;
        }
        return this[validate_error];
    },
    set validate_error(t) {
        this[validate_error]=t;
    },
    get errorAndNeedSuccess() {
        if (!this[errorAndNeedSuccess]) {
            this[errorAndNeedSuccess] = errorAndNeedSuccess;
        }
        return this[errorAndNeedSuccess];
    },
    set errorAndNeedSuccess(t) {
        this[errorAndNeedSuccess]=t;
    },
    get manual_output() {
        if (!this[manual_output]) {
            this[manual_output] = manual_output;
        }
        return this[manual_output];
    },
    set manual_output(t) {
        this[manual_output]=t;
    },
    get requestLogger() {
        if (!this[requestLogger]) {
            this[requestLogger] = CustomLogger(this,this.app.config.userLogger.requestLogger);
        }
        return this[requestLogger];
    },
    get page_index() {
        return this.app.utils.string.toNumber(this.query.pageNo,true) || this.app.utils.string.toNumber(this.query.page_index,true)  || 0;
        // return this.app.utils.string.toNumber(this.query.page_index,true)  || 0;
    },
    get page_size() {
        // return this.app.utils.string.toNumber(this.query.page_size,true) || 0;
        return this.app.utils.string.toNumber(this.query.pageSize,true) || this.app.utils.string.toNumber(this.query.page_size,true) || 0;
    },
    get limit() {
        return this.page_size;
    },
    get offset() {
        return (this.page_index - 1) * this.page_size;
    },
    //定义输出功能，向浏览器输出数据
    outSuccess(msg = '', data = {},response_code_type = null) {
        if (this.app.utils.validator.isNull(data)) {
            data = {};
        }
        if (this.app.utils.validator.isNull(msg)) {
            msg = '';
        }
        this.set('Content-Type', 'application/json;charset=utf-8');
        data =this.format(data);
        this.body = {
            request_id: this.request_id,
            request_url: this.request_url,
            code: this.app.enums.response_code_enum.success.code,
            info: this.app.enums.response_code_enum.success.info,
            msg: msg,
            data: data
        };
    },
    outError(msg = '', data = {}, response_code_type = null) {
        if (this.app.utils.validator.isNull(response_code_type)) {
            response_code_type = this.app.enums.response_code_enum.server_error;
        }
        if (this.app.utils.validator.isNull(data)) {
            data = {};
        }
        if (this.app.utils.validator.isNull(msg)) {
            msg = response_code_type.msg;
        }
        data = this.format(data);
        // this.status =500;
        // this.set("Access-Control-Allow-Origin", "http://127.0.0.1:7001");
        // this.set('Access-Control-Allow-Credentials', 'true');
        this.body = {
            request_id: this.request_id,
            request_url: this.request_url,
            code: response_code_type.code,
            info: response_code_type.info,
            msg: msg,
            data: data
        };
    },
    outNotFound(msg) {
        if(this.app.utils.validator.isNull(msg)){
            msg ='';
        }
        msg = msg || this.app.enums.response_code_enum.not_found.msg;
        this.status =404;
        this.body = {
            request_id: this.request_id,
            request_url: this.request_url,
            code: this.app.enums.response_code_enum.not_found.code,
            info: this.app.enums.response_code_enum.not_found.info,
            msg: msg,
            data: null
        };
    },
    //输出格式化
    format(data){
        if(this.app.utils.validator.isNull(data)){
            data =null;
        }
        var fordata =data;
        var forkey ='';
        try{
            if(!this.app.utils.validator.isNull(data.dataValues)){  //如果是sequelize对象，则取出数据列
                fordata =data.dataValues;
            }
        }catch{}
        
        for (let key in fordata) {
            forkey =key.toLowerCase(); 
            //处理时间格式
            if(forkey.search("time") !=-1 || forkey.search("date") !=-1){
                //将时间戳转为日期
                // fordata[key] =this.app.utils.time.timestampToDate(fordata[key]);
                //将时间日期格式转为字符串
                fordata[key] =this.app.utils.time.format(fordata[key]);
            }
            // if(forkey.indexOf("time") > 0 || forkey.indexOf("date") > 0 ){
            //     fordata[key] =this.app.utils.time.timestampToDate(fordata[key]);
            // }
            //处理特殊数字，如字符串"2.55"转为数字2.5
            // if(this.app.utils.validator.isNum(fordata[key])){
            //     fordata[key] =fordata[key]*1;
            // }
            
            if(this.app.utils.validator.isNum(fordata[key])){
                if(forkey.search("price") !=-1 || forkey.search("money") !=-1 || forkey.search("bonus") !=-1 ){
                    fordata[key] =this.app.utils.number.format(fordata[key],2);
                }else{
                    fordata[key] =fordata[key]*1;
                }               
            }
            
            switch(Object.prototype.toString.call(fordata[key])){
                case '[object Object]':
                case '[object Array]':this.format(fordata[key]);break;
            }
        }
        return fordata;
    },
    validateHandler(error,type){ 
        error =JSON.stringify(error);
        if(type =='params'){     
            this.validate_error =error;
            // this.requestLogger.error(error);
            // s =ss+ `${new Date().toLocaleString()} [${this.ip}] [${this.method} ${this.url}] : ${error} \n`+ss;
            // console.log(s.bgRed); 
        }        
    },
    outValidateStatus(){
        var response_code_type = this.app.enums.response_code_enum.param_error;
        var msg =this.validate_error;
        if (this.app.utils.validator.isNull(msg)) {
            msg = response_code_type.msg;
        }         
        //this.requestLogger.error(msg);     
        // var ss =this.app.config.console.request.style;
        // var s ='';
        // s =ss+ `${new Date().toLocaleString()} [${this.ip}] [${this.method} ${this.url}] : ${msg} \n`+ss;
        // console.log(s.bgRed);
        this.status =501;
        this.body = {
            request_id: this.request_id,
            request_url: this.request_url,
            code: response_code_type.code,
            info: response_code_type.info,
            msg: msg,
            data: {}
        };
    },
    getToken(data){
        var token =this.app.jwt.sign(data, this.app.config.jwt.secret,{
            // expiresIn: eval(this.app.config.jwt.expire)/1000
            expiresIn: eval(this.app.config.jwt.expire)
        });
        return token;
    },
    //构建ant design所需分页数据结构
    convertToAntTableData(data){
        var res =data;     
        if(!this.app.utils.validator.isNull(res)){    
            if(res.hasOwnProperty('rows')){
                res['data'] =res['rows'];            
                this.format(res.data);
            }            
            // res.pageSize =this.page_size;
            // res.pageNo =this.page_index;            
            // res.totalPage = this.app.utils.validator.isNull(res['rows']) ? 0 : res.count % this.page_size == 0 ? res.count / this.page_size : Math.ceil(res.count / this.page_size) || 0;
            // res.totalCount =this.app.utils.validator.isNull(res['rows']) ? 0 : res.count;
            res.page_size =this.page_size;
            res.page_index =this.page_index;            
            res.total_page = this.app.utils.validator.isNull(res['rows']) ? 0 : res.count % this.page_size == 0 ? res.count / this.page_size : Math.ceil(res.count / this.page_size) || 0;
            res.total_count =this.app.utils.validator.isNull(res['rows']) ? 0 : res.count;
            delete res['count'];
            delete res['rows'];
            data =res;
        }        
        return data;
    }
    


};